package com.kehutong.admin.controler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.coraframework.authz.HasPermission;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.ActionResult;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.jdbc.JdbcSession;

import com.kehutong.admin.dao.DictDao;
import com.kehutong.admin.entity.Dict;

@MvcAction
@ReqMapping("/admin/sys/dict")
public class DictController {

    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private DictDao dictDao;


    @HasPermission("sys:dict:view")
    @ReqMapping("/list")
    public Object list(JSONObject jsonObject) {
        return jdbcSession.findPage(Dict.class)
	    		.eq(jsonObject, "type")
	    		.like(jsonObject, "description")
	    		.eq("deleted", false)
	    		.order("type", "ASC")
	    		.order("sort", "desc")
	    		.page(jsonObject)
	    		.exe();
    }
    
    @HasPermission("sys:dict:view")
    @ReqMapping("/get")
    public Object getById(Dict dict) {
        return dict;
    }

    @Bean(newInstance=true, copy=true)
    @HasPermission("sys:dict:edit")
    @ReqMapping("/save")
    public Object save(Dict dict) {
    	jdbcSession.insert(dict);
        
        return Result.success(dict);
    }

//    @TrasIntercepter("/admin/test")
    @Bean(copy=true)
    @HasPermission("sys:dict:edit")
    @ReqMapping("/update")
    public Object update(Dict dict) {
    	jdbcSession.updateById(dict);
    	
        return Result.success();
    }

    @HasPermission("sys:dict:edit")
    @ReqMapping("/delete")
    public Object deleteById(Dict dict) {
    	dict.setDeleted(Boolean.TRUE);
    	jdbcSession.updateById(dict);
    	
    	return Result.success();
    }
    
    @HasPermission("sys:dict:view")
    @ReqMapping("/type")
    public ActionResult<String> type(JSONObject jsonObject) {
//    	 final String sql = "select distinct(type) as type from sys_dict where deleted = false order by type;";
//    	 
//         List<String> typeList = jdbcSession.findList(false, sql, (rs)->rs.getString(1));
    	List<Map<String, Object>> types = dictDao.listTypes();
         List<String> typeList = new ArrayList<>(types.size());
         types.forEach(map->{typeList.add((String)map.get("type"));});
        return Result.success(typeList);
    }

}
